//
//  LogoChangeViewController.m
//  CarTown
//
//  Created by xionghao on 15/9/6.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "LogoChangeViewController.h"
#import "LCActionSheet.h"
#import "Puser.h"
#import "SDPhotoBrowser.h"
#import <UIButton+WebCache.h>
#import "IWUploadParam.h"
#import "AppDelegate.h"
#import "UserInfoUpdateResde.h"
@interface LogoChangeViewController ()< UIImagePickerControllerDelegate,UINavigationControllerDelegate,LCActionSheetDelegate,SDPhotoBrowserDelegate>{
    BOOL _needupload;
}
@property (weak, nonatomic) IBOutlet UIView *bgview;
@property (weak, nonatomic) IBOutlet UIButton *iconbtn;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) UIImagePickerController *picker;


@end

@implementation LogoChangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title=@"修改门头Logo";
    if ([self.user.power integerValue]!=8) {
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
    }
    
    NSLog(@"%@",self.user.shop_logo);
    
    [self.iconbtn sd_setImageWithURL:[NSURL URLWithString:[NSString getImageURLstr:self.user.shop_logo]]  forState:UIControlStateSelected placeholderImage:[UIImage imageNamed:@"placehoder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (![self.user.shop_logo isEqualToString:@""]&&self.user.shop_logo) {
            self.iconbtn.selected=YES;
        }
    }];
    
}
-(void)rightclick{
    
    
    if (_needupload) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"正在上传..";
        hud.mode = MBProgressHUDModeIndeterminate;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        IWUploadParam *new_ico=[[IWUploadParam alloc]init];
        new_ico.data= [UIImage compressData:self.iconbtn.currentImage toMaxFileSize:DefailutPicSize];
        new_ico.mineType=@"jpeg";
        
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"user_type"]=@"company";
        if (self.user.parent_id&&![self.user.parent_id isEqualToString:@"0"]) {
            params[@"com_id"]=self.user.parent_id;
        }else{
            params[@"com_id"]=self.user.com_id;
        }
    params[@"action"]=@"c_logo_change";
            new_ico.paramName=@"new_logo";
            new_ico.fileName=@"new_logo.jpg";
        
        
        
        
        [PostUitls upload:userinfourl parameters:params uploadarray:@[new_ico] success:^(id responseobj) {
            NSDictionary *dict=responseobj;
            UserInfoUpdateResde *resmode=[UserInfoUpdateResde  resdeWithDict:dict];
            if ([resmode.state intValue]==400) {
              
                    self.user.shop_logo=resmode.data;
                
    
                
                AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
                [delegate saveContext];
                hud.mode=MBProgressHUDModeText;
                hud.labelText=@"上传成功";
                
            }else{
                hud.labelText=@"上传失败";
            }
            [hud hide:YES afterDelay:0.5];
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            hud.mode=MBProgressHUDModeText;
            hud.labelText=@"网络错误";
            [hud hide:YES afterDelay:0.5];
        }];

    }
    

}
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

- (IBAction)iconclick:(id)sender {
    if (self.iconbtn.isSelected) {
        [self showHasActionSheet:0];
    }else{
        [self showActionSheet:0];
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(UIImagePickerController *)picker{
    if (_picker==nil) {
        _picker=[[UIImagePickerController alloc]init];
        _picker.view.backgroundColor = [UIColor whiteColor];
        
        _picker.delegate =self;
        _picker.allowsEditing = YES;
    }
    return _picker;
}
-(void)showCarmera:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
    self.picker.view.tag=tag;
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)showimagepiker:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.picker.view.tag=tag;
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}

-(void)showActionSheet:(NSInteger)tag{
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:@[@"拍照",@"从相册中选取"] redButtonIndex:-1 delegate:self];
    sheet.tag=tag;
    [sheet show];
}
-(void)showHasActionSheet:(NSInteger)tag{
    
    NSArray *titles;
    if ([self.user.power integerValue]==8) {
        titles=@[@"查看大图"];
    }else{
        titles=@[@"查看大图",@"重新上传"] ;
    }
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:titles redButtonIndex:-1 delegate:self];
    sheet.tag=tag;
    sheet.isTag=YES;
    [sheet show];
}
-(void)shoWImage:(NSInteger)index{
    SDPhotoBrowser *browser=[[SDPhotoBrowser alloc]init];
    
    browser.sourceImagesContainerView = self.bgview; // 原图的父控件
    browser.imageCount = 1 ; // 图片总数
    browser.currentImageIndex = 0;
    browser.delegate = self;
    [browser show];
    
}
-(UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    return self.iconbtn.currentImage;
}

#pragma actionshseet代理方法
-(void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==actionSheet.btnCount-1) return;
    if (actionSheet.isTag) {
        switch (buttonIndex) {
            case 0:
                [self shoWImage:actionSheet.tag];
                
                break;
            case 1:
                [self showActionSheet:actionSheet.tag];
                break;
         
               
            default:
                break;
        }
        
        
    }else{
        [self showPickerOrCanmra:self.iconbtn WithIndex:buttonIndex];
    }
    
}

-(void)btnclick:(UIButton *)btn{
    if (btn.isSelected) {
        [self showHasActionSheet:btn.tag];
    }else{
        [self showActionSheet:btn.tag];
    }
}
-(void)showPickerOrCanmra:(UIButton *)button WithIndex:(NSInteger)index{
    
    if (index==0) {
        [self showCarmera:button.tag];
    }else{
        [self showimagepiker:button.tag];
    }
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        [self.iconbtn setImage:image forState:UIControlStateSelected];
        self.iconbtn.selected=YES;
        _needupload=YES;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
+(instancetype)viewcontroller{
    LogoChangeViewController *logovc=[[LogoChangeViewController alloc]initWithNibName:NSStringFromClass([self class]) bundle:nil];
    return logovc;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
